import React, { Fragment } from 'react';
import { Menu } from 'antd';
import _ from 'lodash'
import { ClickParam } from 'antd/lib/menu';

const { SubMenu } = Menu;

export interface Node {
    key?: string,
    icon?: string,
    value: string,
    children?: Node[]
    [key: string]: any
}

interface IProp {
    dataSource?: Node[],
    onClick?: Function
}

interface IState {

}

export class YvMenu extends React.Component<IProp, IState> {

    constructor(prop: IProp) {
        super(prop);
    }

    buildMenu(node: Node): any {
        if (node.children && node.children.length > 0) {
            // 有子节点，构造 SubMenu
            return (
                <SubMenu
                    key={node.key}
                    title={
                        <div>
                            {node.icon ? <i className={node.icon} /> : <Fragment />}
                            <span>{node.value}</span>
                        </div>
                    }
                >
                    {
                        _.map(node.children, (node) => this.buildMenu(node))
                    }
                </SubMenu>
            );
        }

        // 没有子节点，构造 Menu.Item
        return (
            <Menu.Item key={node.key} onClick={this.onClick(node)}>
                {node.icon ? <i className={node.icon} /> : <Fragment />}
                <span>{node.value}</span>
            </Menu.Item>
        );
    }

    onClick(node: any): ((param: ClickParam) => void) | undefined {
        const that = this
        return (param: any) => {
            if (this.props.onClick) {
                this.props.onClick.call(that, node, param)
            }
        }
    }

    render() {
        return (
            <Menu mode="inline" theme="dark">
                {
                    _.map(this.props.dataSource, node => {
                        return this.buildMenu(node)
                    })
                }
            </Menu>
        );
    }
}